package com.clkj.nangang.util;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageView;

import com.clkj.nangang.app.CustomApplication;
import com.clkj.nangang.http.DownPicService;
import com.clkj.nangang.util.schedulers.SchedulerProvider;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/12/22.
 */

public class PhotoUtil {

    public static Uri createImageFile() {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = null;
        try {
            image = File.createTempFile(imageFileName,  // prefix
                    ".jpg",         // suffix
                    storageDir);     // directory
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Save a file: path for use with ACTION_VIEW intents
        return Uri.fromFile(image);
    }

    public static void copyFileUsingFileChannels(File source, File dest) {
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            try {
                inputChannel = new FileInputStream(source).getChannel();
                outputChannel = new FileOutputStream(dest).getChannel();
                outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } finally {
            try {
                inputChannel.close();
                outputChannel.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void saveBitmapFromImageView(final ImageView view){

        Bitmap bitmap =((BitmapDrawable) view.getDrawable()).getBitmap();

        //将Bitmap 转换成二进制，写入本地

        Observable.just(bitmap)
                .map(new Func1<Bitmap, File>() {
                    @Override
                    public File call(Bitmap bitmap) {
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.PNG , 100 , stream);
                        byte[] byteArray = stream.toByteArray();
                        File dir = new File(Environment.getExternalStorageDirectory ().getAbsolutePath());
                        if(!dir.isFile()){
                            dir.mkdir();
                        }
                        File file = new File(dir,System.currentTimeMillis() +".png" );
                        try {
                            FileOutputStream fos = new FileOutputStream(file);
                            fos.write(byteArray, 0 , byteArray.length);
                            fos.flush();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return file;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<File>() {
                    @Override
                    public void call(File file) {
                        Intent intent = new Intent(Intent. ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(file);
                        intent.setData(uri);
                        view.getContext().sendBroadcast(intent);
                        ToastUtil.showShort(view.getContext(),"保存成功");
                    }
                });
    }

    public static void downPicFromUrl(String picUrl){

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://app.cangbt.com")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        DownPicService service = retrofit.create(DownPicService.class);
        service.downPicFromUrl(picUrl)
                .subscribeOn(SchedulerProvider.getInstance().io())
                .map(new Func1<ResponseBody, String>() {
                    @Override
                    public String call(ResponseBody body) {
                        try {
                            Log.d("DownloadImage", "Reading and writing file");
                            InputStream in = null;
                            FileOutputStream out = null;

                            try {
                                in = body.byteStream();

                                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                                String imageFileName = "JPEG_" + timeStamp + "_";

                                out = new FileOutputStream(Environment.getExternalStorageDirectory ().getAbsolutePath()
                                        + File.separator + imageFileName + ".jpg");
                                int c;

                                while ((c = in.read()) != -1) {
                                    out.write(c);
                                }

                            }
                            catch (IOException e) {
                                Log.d("DownloadImage",e.toString());
                                return "false";
                            }
                            finally {
                                if (in != null) {
                                    in.close();
                                }
                                if (out != null) {
                                    out.close();
                                }

                            }

                            return "true";

                        } catch (IOException e) {
                            Log.d("DownloadImage",e.toString());
                            return "false";
                        }
                    }
                })
                .observeOn(SchedulerProvider.getInstance().ui())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String saved) {
                        if (saved.equals("true"))
                            ToastUtil.showShort(CustomApplication.globeContext,"保存成功");
                    }
                });

    }

//    public static Bitmap downPicToBitmap(String picUrl){
//
//        final Bitmap[] picBitmap = {null};
//
//        Retrofit retrofit = new Retrofit.Builder()
//                .baseUrl("http://app.cangbt.com")
//                .addConverterFactory(GsonConverterFactory.create())
//                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
//                .build();
//        DownPicService service = retrofit.create(DownPicService.class);
//        service.downPicFromUrl(picUrl)
//                .subscribeOn(SchedulerProvider.getInstance().io())
//                .map(new Func1<ResponseBody, Bitmap>() {
//                    @Override
//                    public Bitmap call(ResponseBody responseBody) {
//                        byte[] bytes = new byte[0];
//                        try {
//                            bytes = responseBody.bytes();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//
//                        return BitmapFactory.decodeByteArray(bytes,0,bytes.length);
//                    }
//                })
//                .observeOn(SchedulerProvider.getInstance().ui())
//                .subscribe(new Action1<Bitmap>() {
//                    @Override
//                    public void call(Bitmap bitmap) {
//                        picBitmap[0] = bitmap;
//                    }
//                });
//        return picBitmap[0];
//    }

}
